import React, { useRef, FC ,useState,useEffect,useImperativeHandle,forwardRef} from 'react'
import { withRouter } from 'react-router-dom'
import commom from '@/api'
import $axios from '@/utils/axios'
import { Table , Modal ,Form,Spin ,Input, Button} from 'antd';
import MyDefineSelect from '@/components/common/myDefineSelect'
import {modalLayoutSm} from '@/config/layout';
import UserOrg from '@/api/userorg'
import {UserOrgCom} from '@/pages/sysMan/user/list'
const RoleList: FC = () => {
  const tableRef: RefType = useRef()
  const [data,setdata] = useState([]);
  const [menyType,setmenyType] = useState({});
  const userOrgEdit: RefType = useRef()
  const OrgEditRef: RefType = useRef()
  useEffect(()=>{
    getOrg();
    getOrgType();
  },[])
  const getOrg = ()=>{
    $axios.get('/dm/api/sys/org/list/tree').then((res)=>{
      let data = res['data']?res['data']:[];
      data = handledata(data);
      setdata(res['data']);
    })
 }
 const handledata = (data)=>{
    data.map((e,i)=>{
      data[i]['key'] = e['deptId']?e['deptId']:e['corpId'];
      let deptVo = e['deptVo']?e['deptVo']:[]
      let children = deptVo.concat(e['children']);
      let title = e['corpName']||e['deptName']
      let deptShortName = e['corpShortName']||e['deptShortName']
      let type = e['corpName']?2:1
      let sub = e['supCorpId']||e['supDept']
      data[i]['title'] = title;
      data[i]['type'] = type;
      data[i]['sub'] = sub;
      data[i]['deptShortName'] = deptShortName;
      if(children.length==0){
        let obj = Object.assign(e,{});
        delete obj['children'];
        delete obj['deptVo'];
        data[i] = obj;
      }else{
        let childrennew = handledata(children);
        
        data[i]['children'] = childrennew;
      }
    })

    data.sort((a,b)=>{
      return a['sno']-b['sno'];
    })
    console.log(data);
    return data;
 }
 const getOrgType = ()=>{
  $axios.post('/dm/api/sys/dict/selectDictLabel',{
    dictindex: "OrgType",
    pageNum: 1,
    pageSize: 10000,
  }).then((res)=>{
    let OrgtypeObj ={};
    let data = res['data']['list']?res['data']['list']:[];
    data.map((e)=>{
      OrgtypeObj[e['optionvalue']] = e['optionlabel'];
    })
    setmenyType(OrgtypeObj)

  })
}

   // 添加
   const addGroup = (record:any) => {
    userOrgEdit.current.init('',record,1,record.key,record.sub);
  }
  // 添加
  const addComp = (record:any) => {
    userOrgEdit.current.init('',record,2,record.key,record.sub);
  }
  
   // 修改
   const editGroup = (record:any) => {

    userOrgEdit.current.init(record.key,record,record.type,record.sub);
  }
  // 删除
  const delGroup = (record:any) => {
    let type = record.type;
    Modal.confirm({
      title: '确认删除',
      
      onOk() {
        if(type==1){
          UserOrg.deleteDept({
            deptId:record.deptId
          }).then(()=>{
            getOrg();
          })
        }else{
          UserOrg.deleteCompany({
            corpId:record.corpId,
          }).then(()=>{
            getOrg();
          })
        }
       
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }
 const columns = [
  {
    title: '名称',
    key: 'title',
    dataIndex: 'title',
    width:300
  },
  {
    title: '简称',
    key: 'deptShortName',
    dataIndex: 'deptShortName',
  },
  {
    title: '类型',
    key: 'type',
    dataIndex: 'type',
    render:(txt,record,index)=>{
      return !record.deptId?'公司':'组织'
    } 
  },
  {
    title: '操作',
    key: 'scan',
    dataIndex: 'scan',
    width: "300px",
    render:(txt,record,index)=>{
      return <>
        <a onClick={() => editGroup(record)} style={{ marginRight: '10px' }}>编辑</a>
        <a onClick={() => delGroup(record)} style={{ marginRight: '10px' }}>删除</a>
        {
          !record.deptId&&<a onClick={() => addComp(record)} style={{ marginRight: '10px' }}>新增子公司</a>
        }
        
        <a onClick={() => addGroup(record)} >新增子组织</a>
      </>
     
    }
  },
]
  return (
    <>
    <div style={{textAlign:'right',marginBottom:'10px'}}>
     <Button type="primary" onClick={()=>addComp('')}>新增公司</Button>
    </div>
    
    <Table
      bordered={true}
      pagination={false}
      columns={columns}
      dataSource={data}
      scroll={{
        y:window.innerHeight-260
      }}
    />
    <OrgEditCom ref={OrgEditRef} callback={()=>{
        getOrg();
      }}/>
    <div style={{height:'15px'}}></div>
    <UserOrgCom ref={userOrgEdit} callback={()=>{
        getOrg();
      }}/>
  </>
  )
}



//菜单
const OrgEdit = (props, refs) => {
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [form] = Form.useForm();
  const [loading, setLoading] = useState<boolean>(false)
  //菜单id
  const [Orgid,setOrgid] = useState('');
  //父id
  const [upperOrg,setupperOrg] = useState('');
  //父菜单name
  const [upperOrgname,setupperOrgname] = useState('');
  const { setFieldsValue, resetFields } = form;
  useImperativeHandle(refs, () => ({
    // 菜单id   Orgid_q
    // 父菜单id  upperOrg_q
    init: (Orgid_q,upperOrg_q,setupperOrgname_q) => {
      setOrgid(Orgid_q);
      setupperOrg(upperOrg_q);
      setupperOrgname(setupperOrgname_q)
      if(Orgid_q){
        $axios.get('/dm/api/Org/detail?Orgid='+Orgid_q).then((res)=>{
          let data = res['data'];
          setFieldsValue({
            Orgname:data['Orgname'],
            Orgkey:data['Orgkey'],
            Orgpath:data['Orgpath'],
            Orgtype:data['Orgtype'],
            sno:data['sno']
          })
        })
      }else{
        resetFields();
      }
      showModal();
    }
  }))

  //显示弹窗
  const showModal = () => {
    setIsModalVisible(true);
  };
  //确定
  const handleOk = () => {
    form.validateFields().then((vals) => {
      setLoading(true);
      const Obj = form.getFieldsValue()

      let fn = Orgid? $axios.put: $axios.post;
      let url = Orgid?'/dm/api/Org/edit':'/dm/api/Org/add';
      let param = Orgid?{
        ...Obj,
        ...{
          Orgid:Orgid,
          upperOrg:upperOrg
        }
      }:{
        ...Obj,
        ...{
          upperOrg:upperOrg
        }
      }
      fn(url,param).then((res)=>{
        handleCancel();
      }).catch(()=>{
        setLoading(false);
      })
      
    })
  };
  const handleCancel = () => {
    setIsModalVisible(false);
    setLoading(false);
    props.callback&&props.callback();
  };

  return <Modal 
  title={Orgid?'新增菜单':'修改菜单'} 
  visible={isModalVisible} 
  onOk={handleOk} 
  onCancel={handleCancel}
  width={650}
  maskClosable={false}
  >

    <Spin spinning={loading}>
      <Form form={form} {...modalLayoutSm}>
        <Form.Item
          name="Orgname"
          label="菜单名称"
          rules={[
            {
              required: true,
              message: '请输入菜单名称'
            }
          ]}
        > 
          <Input />
        </Form.Item>
        <Form.Item
          name="Orgkey"
          label="菜单key"
          rules={[
            {
              required: true,
              message: '请输入菜单key'
            }
          ]}
        > 
          <Input />
        </Form.Item>
        <Form.Item
          name="Orgpath"
          label="菜单路径"
          rules={[
            {
              required: true,
              message: '请输入菜单路径'
            }
          ]}
        > 
          <Input />
        </Form.Item>
        <Form.Item
          name="Orgtype"
          label="菜单类型"
          rules={[
            {
              required: true,
              message: '请选择菜单类型'
            }
          ]}
        > 
           <MyDefineSelect 
              url="/dm/api/sys/dict/selectDictLabel"
              params={{'dictindex':"OrgType"}}
              namekey="optionlabel"
              idkey="optionvalue"
              requestMethod="post"
              formatIdKey={(key)=>{return key}}
            />
        </Form.Item>
        <Form.Item
          name="sno"
          label="菜单排序"
          rules={[
            {
              required: true,
              message: '请输入菜单排序'
            }
          ]}
        > 
          <Input />
        </Form.Item>
      </Form>
    </Spin>
  </Modal>
}


const OrgEditCom = forwardRef(OrgEdit);





export default withRouter(RoleList)
